#include "common.h"
int main()
{
    //创建命名管道
    umask(0);
    if(mkfifo(FILE_NAME,0666) < 0)
    {
        perror("mkfifo");
        return 1;
    }
    //管道创建成功
    //读端打开管道文件
    int fd = open(FILE_NAME,O_RDONLY);
    if(fd < 0)
    {
        perror("open");
        return 1;
    }
    char msg[128];
    while(1)
    {
        //读端重复读取命名管道
        msg[0] = '\0';
        ssize_t size = read(fd,msg,sizeof(msg)-1);
        if(size > 0)
        {
            //说明此时管道中存在数据
            //对信息进行解析
            msg[size] = '\0';
            printf("client say: %s\n",msg);
            char* label = "+-*/%";
            char* p = msg;
            int flag = 0;
            while(*p)
            {
                //获取是什么符号
                switch(*p)
                {
                    case '+':
                        flag = 0;
                        break;
                    case '-':
                        flag = 1;
                        break;
                    case '*':
                        flag = 2;
                        break;
                    case '/':
                        flag = 3;
                        break;
                    case '%':
                        flag = 4;
                        break;
                }
                p++;
            }
            //解析出两个数字
            char* snum1 = strtok(msg,"+-*/%");
            char* snum2 = strtok(NULL,"+-*/%");
            int num1 = atoi(snum1);
            int num2 = atoi(snum2);
            int ret = 0;
            switch (flag)
            {
                case 0:
                    ret = num1 + num2;
                    break;
                case 1:
                    ret = num1 - num2;
                    break;
                case 2:
                    ret = num1 * num2;
                    break;
                case 3:
                    ret = num1 / num2;
                    break;
                case 4:
                    ret = num1 % num2;
                    break;
            }
            //打印计算结果
            printf("%d %c %d = %d\n",num1,label[flag],num2,ret);
        }
        else if(size == 0)
        {
            printf("client quit\n");
            break;
        }
        else 
        {
            printf("read error");
            break;
        }
    }
    close(fd);
    return 0;
}